// ============================================================================
//
// Graph framework by Aurelien Moreau aurelien.moreau@gmail.com
// Modified by Pierre CHATEL chatelp@gmail.com
// Distributed under LGPL
// Copyright (C) Aurelien Moreau, 2008, 2009. All rights reserved
//
// ============================================================================

package com.thalesgroup.graphFramework.core.utils;

import java.io.Reader;
import java.util.HashMap;
import java.util.Iterator;

import com.thalesgroup.graphFramework.core.Edge;
import com.thalesgroup.graphFramework.core.Graph;
import com.thalesgroup.graphFramework.core.GraphBuilder;
import com.thalesgroup.graphFramework.core.Vertex;
import com.thalesgroup.graphFramework.core.impl.GraphBuilderImpl;


public class DOTTools<V,E> {
	private GraphBuilder<V, E> builder;

	public DOTTools() {
		builder=new GraphBuilderImpl<V, E>();
	}
	
	public void graph2dot(Graph<V,E> graph, StringBuffer out) {
		
		out.append("digraph G {\n");
		
		for(Iterator<Vertex<V,E>> i=graph.getVertices(); i.hasNext();) {
			Vertex<V,E> v=i.next();
			out.append("\t");
			out.append("n");
			out.append(v.getIndex());
			out.append("[");
			feature(v, out);
			out.append("];\n");
		}
	
		for(Iterator<Edge<V,E>> i=graph.getEdges(); i.hasNext();) {
			Edge<V,E> e=i.next();
			
			Vertex<V,E> src=e.getIn();
			Vertex<V,E> tgt=e.getOut();
			
			out.append("\t");
			
			out.append("n");
			out.append(src.getIndex());
			out.append("->");
			out.append("n");
			out.append(tgt.getIndex());
			
			out.append("[");
			feature(e, out);
			out.append("];\n");
		}
		
		out.append("}");
	}

	protected void feature(Vertex<V,E> v, StringBuffer out) {
		if(v.getVertex()!=null) {
			out.append("label=\"");
			out.append(v.getVertex().toString());
			out.append("\" ");
		}
	}
	
	protected void feature(Edge<V,E> e, StringBuffer out) {
		if(e.getEdge()!=null) {
			out.append("label=\"");
			out.append(e.getEdge().toString());
			out.append("\" ");
		}
	}
	
	public Graph<V,E> dot2Graph(Reader reader) {
		builder.createNewGraph();
	
		HashMap<String, Vertex<V,E>> vertices=new HashMap<String, Vertex<V,E>>();
		
		//BufferedReader breader=new BufferedReader(reader);
		
		
		
		
		
		
		builder.finalizeGraph();
		return builder.getCurrentGraph();
	}
	
	

}
